try: import json #python 2.6 included simplejson as json
except ImportError: import simplejson as json

def write_properties(json_data, options):
    if options.properties:
        props = options.properties.split(":")
        for prop in props:
            if "=" in prop:
                key = prop.split("=")[0]
                val = prop.split("=")[1]
                json_data[key] = val

def list_items(dataset_id):
    json_data = load(dataset_id)

    print "Properties:"
    for key in json_data:
        val = json_data[key]
        if not isinstance(val, (list, dict)):
            print "\t" + key + "=" + str(val)

    print_items("Features", "features", json_data)
    print_items("Samples", "samples", json_data)
    print_items("Annotations", "annotations", json_data)
    print_items("Statistics", "statistics", json_data)
    print_items("References", "references", json_data)
    print_items("Associations", "associations", json_data)
    print_items("Feature Matrices", "featurematrix", json_data)

def print_items(header, key, json_data):
    print header + ":"

    if key in json_data:
        json_data_array = json_data[key]
        for item in json_data_array:
            if "id" in item:
                if "label" in item:
                    if item["id"] == item["label"]:
                        print "\t - " + item["id"]
                    else:
                        print "\t - " + item["id"] + ": (" + item["label"] + ")"
                else:
                    print "\t - " + item["id"]
            if "schema" in item:
                for schemaitem in item["schema"]:
                    print "\t\t - " + schemaitem["name"] + " [" + schemaitem["type"] + "]: (" + schemaitem["label"] + ")"

def save(dataset_id, json_data):
    json_data["id"] = dataset_id
    wfile = open(dataset_id + "/dataset.json", "w")
    wfile.write(json.dumps(json_data, indent=4) + "\n")
    wfile.close()

lookup_data_types = ["features", "samples", "annotations", "references", "associations", "featurematrix"]
def lookup_item(dataset_id, item_id):
    json_data = load(dataset_id)
    for data_type in lookup_data_types:
        if data_type in json_data:
            for item in json_data[data_type]:
                if "id" in item and item["id"] == item_id: return item, json_data

    print "===> ERROR: Item not found in Dataset [" + dataset_id + "," + item_id + "]"
    list_items(dataset_id)
    exit(-1)

def load(dataset_id):
    return json.load(open(dataset_id + "/dataset.json"))
